package com.example.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.controller.util.Data;
import com.example.domain.Activity;
import com.example.domain.Reservation;
import com.example.domain.Volunteer;
import com.example.mapper.ReservationMapper;
import com.example.service.IActivityService;
import com.example.service.ReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IActivityService activityService;
    @Override
    public IPage<Reservation> getPageReservation(Integer page, Integer size, Integer status) {
        IPage<Reservation> pageInfo = new Page<>(page, size);
        LambdaQueryWrapper<Reservation> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getStatus,status);
        reservationMapper.selectPage(pageInfo,queryWrapper);
        return pageInfo;
    }

//    根据状态查询
    @Override
    public List<Reservation> getReservationByStatus(Integer id, Integer status) {
        QueryWrapper<Reservation>  queryWraper = new QueryWrapper<>();
        //volunteer_id数据库字段
        queryWraper.eq("volunteer_id",id);
        queryWraper.eq("status",status);
        List<Reservation> list = reservationMapper.selectList(queryWraper);
        return list;
    }

    /**
     * 用户提交报名申请！
     * @param reservation
     * @return
     */
    @Override
    public Data commitReservation(Reservation reservation) {
        LambdaQueryWrapper<Activity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Activity::getActivityId,reservation.getActivityId());
        Activity activity = activityService.getOne(queryWrapper);
        String registrationTime = activity.getRegistrationTime();
        String[] list = registrationTime.split(">");
        String start=list[0];
        String end=list[1];
//        开始时间
        LocalDate startTime = LocalDate.parse(start);
//        结束时间
        LocalDate endTime = LocalDate.parse(end);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//       当前时间
        LocalDate localTime=LocalDate.now();

//       判断活动是否进行中
        if (localTime.isBefore(startTime)){
            return new Data(300,"报名活动未开启！");
        }
        if (localTime.isAfter(endTime)){
            return new Data(301,"报名活动已结束！");
        }
        reservationMapper.insert(reservation);
        return new Data(200,"您已预约！请等待管理员审核！");
    }

    @Transactional
    @Override
    public Data examine(Reservation reservation) {
//1.如果拒绝通过报名，不需判断people
        if (reservation.getStatus() == 0){
            int result=reservationMapper.updateById(reservation);
            Integer code = result >= 1 ? 200 : 405;
            String msg= result >= 1 ? "已拒绝" : "审核失败，请重试！";
            return new Data(code ,msg);
        }
//2.审核通过报名，通过getActivityID获取people存入redis-1判断判断库存是否充足
        LambdaQueryWrapper<Activity> queryWrapper=new LambdaQueryWrapper<>();
        Integer activityId=reservation.getActivityId();
        queryWrapper.eq(Activity::getActivityId,activityId);
        //获取活动人数，并存入redis中，每次-1，
        int people = activityService.getOne(queryWrapper).getPeople();
        String strPeople=people+"";
        redisTemplate.opsForValue().setIfAbsent(reservation.getActivityId().toString(),strPeople);
        redisTemplate.expire(reservation.getActivityId().toString(),1,TimeUnit.MINUTES);
        //increment要放在boundValue前，否则无效
        redisTemplate.opsForValue().decrement(reservation.getActivityId().toString(),1);
        //在redis中存入数字，需要用boundValueOps().get(start,end)取出
        String stock=redisTemplate.boundValueOps(reservation.getActivityId().toString()).get(0,-1);
        int stockPeople = Integer.parseInt(stock);
        System.out.println(stock);
        //判断剩余人数是否充足！
        if (stockPeople < 0){
            return new Data(302,"报名人数已满！");
        }
        //修改状态！
        reservationMapper.updateById(reservation);
        return new Data(200,"审核已通过！");
    }
}
